import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'

const initialState = createSlice({
    name: 'foods',
    initialState: {
        foodsList: [],
        activeIndex: 0,
    },
    reducers: {
        setFoodsList(state, action) {
            state.foodsList = action.payload
        },
        changeActiveIndex(state, action) {
            state.activeIndex = action.payload
        }
    }
})

const { setFoodsList, changeActiveIndex } = initialState.actions
// 异步获取部分
const fetchFoodsList = () => {
    return async (dispatch) => {
        // 编写异步逻辑
        // const res = await axios.get('http://localhost:3001/foods');
        // 调用dispatch函数提交action
        dispatch(setFoodsList([1,2,3,4]));
    }
}

export {
    fetchFoodsList,
    changeActiveIndex
}

const reducers = initialState.reducer

export default reducers